from django.http import JsonResponse
from django.shortcuts import render
from django.template import loader
from apps.contents.models import ContentCategory
from apps.goods.models import GoodsCategory, GoodsChannel


# 封装方法进行调用
def get_category():
    data_dict = {}
    # 获取所有商品分组信息，按照分组id和组内顺序排序
    channels = GoodsChannel.objects.all().order_by('group_id', 'sequence')
    for channel in channels:
        # 提取分组id信息
        group_id = channel.group_id
        # 判断group_id是否已经在字典中存在
        if group_id not in data_dict:
            # 使用group_id作为data_dict的key值进行赋值
            data_dict[group_id] = {'channels': [], 'sub_cats': []}
        # 使用商品频道对象关联查询分类表的数据
        cat1 = channel.category
        data_dict[group_id]['channels'].append({
            'id': cat1.id,  # 一级分类id
            'name': cat1.name,  # 一级分类名称
            'url': channel.url
        })
        # 根据一级分类获取二级分类信息
        cat2s = GoodsCategory.objects.filter(parent_id=cat1.id)
        for cat2 in cat2s:
            # 额外cat2对象赋值一个空列表
            cat2.sub_cats = []
            # 根据二级分类查询三级分类
            cat3s = GoodsCategory.objects.filter(parent_id=cat2.id)
            for cat3 in cat3s:
                cat2.sub_cats.append({
                    'id': cat3.id,
                    'name': cat3.name
                })
            # 添加二级分类
            data_dict[group_id]['sub_cats'].append({
                'id': cat2.id,
                'name': cat2.name,
                'sub_cats': cat2.sub_cats  # 给三级分类赋值
            })
    return data_dict


def create_index_html():
    data_dict = get_category()
    # 广告数据
    # {'广告类别1':[],'类别2':[]}
    contents = {}
    # 查询广告类别表
    content_catgories = ContentCategory.objects.all()
    # 遍历广告类别
    for content_catgory in content_catgories:
        # 根据广告类别查询广告内容，主表查询副表的关联查询
        contents[content_catgory.key] = content_catgory.content_set.filter(status=True).order_by('sequence')
    # 将data_dict进行渲染
    context = {'categories': data_dict, 'contents': contents}
    # 将首页渲染的html数据写入到前端的index.html文件中，方便用户访问前端看到渲染后的数据
    # response = render('','index.html', context=context)
    # 生成模版对象
    template = loader.get_template('index.html')
    html_str = template.render(context)
    with open('/home/ubuntu/Desktop/front_end_pc/index.html', 'w') as f:
        f.write(html_str)
